//
//  BackgroundScanner.m
//  com.vida.demo
//
//  Created by Benjamin Hugo on 2013/11/06.
//  Copyright (c) 2013 iota. All rights reserved.
//

#import "BackgroundScanner.h"
NSString * const CS_ON_SCAN = @"SCANNER_EVENT";
NSString * const CS_ON_SCAN_COMPLETE = @"SCANNER_COMPLETE_EVENT";
@implementation BackgroundScanner
static NSTimer *timer;
+(void) startScanOp{
    @synchronized([self class]){
            NSLog(@"%@",@"execute ");
            //send event to viewers:
            [[NSNotificationCenter defaultCenter] postNotificationName:CS_ON_SCAN object:self];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:CS_ON_SCAN_COMPLETE object:self];
            });
    }
}
+(void) startThread{
    NSLog(@"%@",@"LOOPING ");
    @synchronized([self class]){
            NSThread * background = [[NSThread alloc] initWithTarget:self
                                               selector:@selector(startScanOp)
                                                 object:nil];
            [background start];
            if (timer == nil)
                timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(startThread) userInfo:nil repeats:YES];
    }
}

+(void) startScanning{
    @synchronized([self class]){
        if (timer != nil){
            [timer invalidate];
            timer = nil;
        }
        [BackgroundScanner startThread];
    }
}
+(void) stopScanning{
    @synchronized([self class]){
        if (timer != nil)
            [timer invalidate];
    }
}
@end
